// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import htmlToPdfTest from './htmlToPdfTest'
let PDF = new JsPDF('', 'pt', 'a4');
let currentPage = 0;
const htmlToPdfSingleTest = {
	getPdf: (obj) => {
		return new Promise((resolve, reject) => {
			let title = `${obj.match_name}-${obj.project_name}`
			console.log("#pdfDom" + obj.merchant + "");
			html2Canvas(document.querySelector("#pdfDom" + obj.merchant + ""), {
				async: false,
				// allowTaint: true,
				useCORS: true,
				scale: 2,
				dpi: 300,
			}).then(function (canvasObj) {
				let contentWidth = canvasObj.width;
				let contentHeight = canvasObj.height;
				//一页pdf显示html页面生成的canvas高度;
				let pageHeight = contentWidth / 592.28 * 841.89
				let pageCount = 0
				//未生成pdf的html页面高度
				let leftHeight = contentHeight
				let leftWidth = obj.nums == 0 ? 0 : 16 //32 16 8
				//页面偏移
				let position = 0
				//a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
				let imgWidth = 595.28
				let imgHeight = 592.28 / contentWidth * contentHeight
				let pageData = canvasObj.toDataURL('image/jpeg', 1.0)
				//转img 2 pdf
				// let PDF = new JsPDF('', 'pt', 'a4')
				//有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
				//当内容未超过pdf一页显示的范围，无需分页
				// console.log(obj.merchant)
				// let blob = dataURLtoBlob(pageData);
				// img.src = '' + URL.createObjectURL(blob) + ''
				// debugger;
				if (obj.projectType == 6) {
					PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
					if (currentPage < obj.targetPages) {
						PDF.addPage();
						currentPage++;
					} else {
						PDF.save(title + '.pdf');
						PDF = new JsPDF('', 'pt', 'a4');
						currentPage = 0;
					}
				}
				else {
					let id = document.querySelector("#pdfPrinting")
					let img = document.createElement('img');
					// img.src = '' + pageData + ''
					let blob = dataURLtoBlob(pageData);
					img.src = '' + URL.createObjectURL(blob) + ''
					img.id = "pdfPrinting" + obj.merchant + ""
					// img.style.width = "100%";
					img.style.width = "100%";
					img.style.height = "auto";
					img.style.display = "block";

					id.appendChild(img);

					// setTimeout(() => {
					// 	let height = img.offsetWidth * 841.89/592.28
					// 	if(img.offsetHeight!=0 && img.offsetHeight< height){
					// 		img.style.marginBottom = (height - img.offsetHeight )+"px";
					// 	}
					// 	resolve()
					// }, 0);
					
				}
				resolve()
			})
		})
	},
}

function dataURLtoBlob(dataurl) {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
}
export default htmlToPdfSingleTest
